<template>
    <div class="sales-page">
        <el-container>
            <!-- 顶部筛选区域 -->
            <el-header height="auto">
                <el-card shadow="never">
                    <el-form :inline="true" :model="formInline" label-width="auto" class="filter-form">
                        <el-form-item label="销售单号">
                            <el-input
                                v-model="formInline.salesOrderNo"
                                clearable
                                placeholder="请输入"
                                style="width: 180px"
                            />
                        </el-form-item>
                        <el-form-item label="单据状态">
                            <el-select
                                v-model="formInline.salesOrderStatus"
                                placeholder="请选择"
                                clearable
                                style="width: 160px"
                            >
                                <el-option
                                    v-for="status in SALES_STATUS_OPTIONS"
                                    :key="status.value"
                                    :label="status.label"
                                    :value="status.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="客户名称">
                            <el-select
                                v-model="formInline.customerId"
                                placeholder="请选择"
                                clearable
                                style="width: 220px"
                                filterable
                                remote
                                reserve-keyword
                                :remote-method="handleCustomerSearch"
                                :loading="customerLoading"
                                @visible-change="handleCustomerDropdownVisible"
                            >
                                <el-option
                                    v-for="item in customerOptions"
                                    :key="item.customerId"
                                    :label="item.customerName"
                                    :value="String(item.customerId)"
                                />
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item label="销售日期">
                            <el-date-picker
                                v-model="formInline.dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="YYYY-MM-DD"
                                style="width: 260px"
                                clearable
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-space>
                                <el-button type="primary" @click="handleQuery">查询</el-button>
                                <el-button @click="handleReset">重置</el-button>
                                <el-button @click="advancedVisible = true">高级搜索</el-button>
                            </el-space>
                        </el-form-item>
                    </el-form>
                </el-card>
            </el-header>

            <!-- 列表与工具栏 -->
            <el-main>
                <el-card shadow="never">
                    <div class="toolbar">
                        <el-space wrap>
                            <el-button type="success" size="small" @click="handleCreate">新增</el-button>
                            <el-button size="small" @click="handleBatchDelete">删除</el-button>
                            <el-button size="small" @click="handleCopy">复制</el-button>
                            <el-button size="small" @click="handleAudit">审核</el-button>
                            <el-button size="small" @click="handleExport">导出</el-button>
                            <el-button size="small" @click="handleRefresh">刷新</el-button>
                        </el-space>
                    </div>

                    <el-scrollbar x>
                        <el-table
                            ref="multipleTableRef"
                            :data="tableData"
                            border
                            stripe
                            style="width: 100%"
                            @selection-change="handleSelectionChange"
                            empty-text="暂无数据"
                        >
                            <el-table-column type="selection" width="55" fixed="left" />
                            <el-table-column type="index" label="序号" width="60" fixed="left" />

                            <el-table-column
                                prop="salesOrderNo"
                                label="销售单号"
                                width="160"
                                fixed="left"
                                show-overflow-tooltip
                            >
                                <template #default="{ row }">
                                    <el-link type="primary" @click="goDetail(row)">
                                        {{ row.salesOrderNo }}
                                    </el-link>
                                </template>
                            </el-table-column>

                            <el-table-column prop="salesOrderStatus" label="单据状态" width="100" fixed="left">
                                <template #default="{ row }">
                                    <el-tag :type="getStatusTagType(row.salesOrderStatus)" size="small">
                                        {{ getStatusText(row.salesOrderStatus) }}
                                    </el-tag>
                                </template>
                            </el-table-column>

                            <el-table-column prop="salesOrderDate" label="销售日期" width="120">
                                <template #default="{ row }">
                                    {{ formatDate(row.salesOrderDate) || '-' }}
                                </template>
                            </el-table-column>

                            <el-table-column
                                prop="customerName"
                                label="客户名称"
                                min-width="160"
                                show-overflow-tooltip
                            />
                            <el-table-column
                                prop="salesContact"
                                label="联系人"
                                width="100"
                                show-overflow-tooltip
                            />
                            <el-table-column
                                prop="salesContactPhone"
                                label="联系电话"
                                width="130"
                                show-overflow-tooltip
                            />
                           
                            <el-table-column
                                prop="organizationName"
                                label="销售部门"
                                min-width="140"
                                show-overflow-tooltip
                            />
                            <el-table-column
                                prop="userName"
                                label="销售负责人"
                                width="110"
                                show-overflow-tooltip
                            />

                            <el-table-column
                                prop="salesOrderQuantity"
                                label="销售数量"
                                width="100"
                                align="right"
                            >
                                <template #default="{ row }">
                                    {{ row.salesOrderQuantity }}
                                </template>
                            </el-table-column>
                            <el-table-column
                                prop="salesOrderAmount"
                                label="销售金额"
                                width="120"
                                align="right"
                            >
                                <template #default="{ row }">
                                    <span class="amount-text">
                                        ¥{{ Number(row.salesOrderAmount ?? 0).toFixed(2) }}
                                    </span>
                                </template>
                            </el-table-column>

                            <el-table-column
                                prop="productName"
                                label="销售货品"
                                min-width="220"
                                class-name="goods-column"
                            >
                                <template #default="{ row }">
                                    <div class="goods-multi-text">
                                        <template v-if="row.productDisplayList?.length">
                                            <div
                                                v-for="(name, index) in row.productDisplayList"
                                                :key="`${row.salesOrderId}-goods-${index}`"
                                                class="goods-name-item"
                                            >
                                                {{ name }}
                                            </div>
                                        </template>
                                        <template v-else>
                                            {{ row.productName || '-' }}
                                        </template>
                                    </div>
                                </template>
                            </el-table-column>

                            <el-table-column
                                prop="salesOrderUser"
                                label="制单人"
                                width="100"
                                show-overflow-tooltip
                            />
                            <el-table-column
                                prop="salesOrderDepartment"
                                label="所在部门"
                                min-width="120"
                                show-overflow-tooltip
                            />
                            <el-table-column prop="salesOrderTime" label="制单时间" width="160">
                                <template #default="{ row }">
                                    {{ row.salesOrderTime ? formatDateTime(row.salesOrderTime) : '-' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="createor" label="审核人" width="100" show-overflow-tooltip>
                                <template #default="{ row }">
                                    {{ row.createor || '-' }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="createrTime" label="审核时间" width="160">
                                <template #default="{ row }">
                                    {{ row.createrTime ? formatDateTime(row.createrTime) : '-' }}
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" fixed="right" width="140" align="center">
                                <template #default="{ row }">
                                    <el-button link type="primary" size="small" @click="handleEdit(row)">
                                        编辑
                                    </el-button>
                                    <el-button link type="danger" size="small" @click="handleDelete(row)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-scrollbar>
                </el-card>

                <!-- 分页区域 -->
                <el-card shadow="never" class="pagination-card">
                    <div class="pagination-bar">
                        <div class="pagination-info">
                            共{{ page.listCount }}条， 每页{{ page.pagesize }}条， 当前第{{ page.pageindex }} / {{
                                page.pageCount
                            }}页
                        </div>
                        <div class="pagination-controls">
                            <el-button
                                class="pagination-btn"
                                link
                                type="primary"
                                size="small"
                                @click="page.pageindex = 1"
                            >
                                首页
                            </el-button>
                            <el-pagination
                                v-model:current-page="page.pageindex"
                                v-model:page-size="page.pagesize"
                                :page-sizes="[10, 20, 50, 100]"
                                :total="page.listCount"
                                prev-text="上一页"
                                next-text="下一页"
                                :background="true"
                                layout="prev, pager, next"
                            />
                            <el-button
                                class="pagination-btn"
                                link
                                type="primary"
                                size="small"
                                @click="page.pageindex = page.pageCount || 1"
                            >
                                尾页
                            </el-button>
                            <span class="pagination-jump">
                                前往
                                <el-input-number
                                    v-model="page.pageindex"
                                    :min="1"
                                    :max="page.pageCount || 1"
                                    size="small"
                                    controls-position="right"
                                    style="width: 90px"
                                />
                                页
                            </span>
                        </div>
                    </div>
                </el-card>
            </el-main>
        </el-container>

        <!-- 高级搜索抽屉 -->
        <el-drawer v-model="advancedVisible" title="高级搜索" direction="rtl" size="520px">
            <el-form :model="advancedForm" label-width="90px" class="advanced-form">
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="销售单号">
                            <el-input v-model="advancedForm.salesOrderNo" clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="销售金额">
                            <div class="range-input">
                                <el-input-number v-model="advancedForm.minAmount" :min="0" />
                                <span class="range-separator">~</span>
                                <el-input-number v-model="advancedForm.maxAmount" :min="0" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="销售日期">
                            <el-date-picker
                                v-model="advancedForm.dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="YYYY-MM-DD"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="销售数量">
                            <div class="range-input">
                                <el-input-number v-model="advancedForm.minCount" :min="0" />
                                <span class="range-separator">~</span>
                                <el-input-number v-model="advancedForm.maxCount" :min="0" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="16">
                    <el-col :span="24">
                        <el-form-item label="单据状态">
                            <el-checkbox-group v-model="advancedForm.statusList">
                                <el-checkbox
                                    v-for="status in SALES_STATUS_OPTIONS"
                                    :key="`adv-${status.value}`"
                                    :label="status.value"
                                >
                                    {{ status.label }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="16">
                    <el-col :span="12">
                        <el-form-item label="客户名称">
                            <el-select
                                v-model="advancedForm.customerId"
                                placeholder="请选择"
                                clearable
                                style="width: 100%"
                                filterable
                                remote
                                reserve-keyword
                                :remote-method="handleCustomerSearch"
                                :loading="customerLoading"
                                @visible-change="handleCustomerDropdownVisible"
                            >
                                <el-option
                                    v-for="item in customerOptions"
                                    :key="item.customerId"
                                    :label="item.customerName"
                                    :value="String(item.customerId)"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    
                </el-row>

                <el-row :gutter="16">
                    <el-col :span="12">
                        <el-form-item label="销售部门">
                            <el-input v-model="advancedForm.departmentName" clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="销售负责人">
                            <el-input v-model="advancedForm.userName" clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="16">
                    <el-col :span="12">
                        <el-form-item label="制单人">
                            <el-input v-model="advancedForm.makerName" clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="制单时间">
                            <el-date-picker
                                v-model="advancedForm.makerTimeRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="YYYY-MM-DD"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="16">
                    <el-col :span="12">
                        <el-form-item label="审核人">
                            <el-input v-model="advancedForm.reviewer" clearable placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="审核时间">
                            <el-date-picker
                                v-model="advancedForm.reviewTimeRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                value-format="YYYY-MM-DD"
                                clearable
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <template #footer>
                <div style="text-align: right">
                    <el-button @click="handleAdvancedReset">重置</el-button>
                    <el-button @click="advancedVisible = false">关闭</el-button>
                    <el-button type="primary" @click="handleAdvancedSearch">查询</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { ElMessage, ElMessageBox, type TableInstance } from 'element-plus'
import moment from 'moment'
import router from '@/router'
import myaxios from '@/http/MyAxios'

interface SalesOrderItem {
    salesOrderId: number
    salesOrderNo: string
    salesOrderStatus: number
    salesOrderDate: string
    customerId: number
    customerName: string
    salesContact: string
    salesContactPhone: string
    organizationId: number
    organizationName: string
    userId: number
    userName: string
    productId?: number
    productName?: string
    salesOrderQuantity: number
    salesOrderAmount: number
    salesOrderUser?: string
    salesOrderDepartment?: string
    salesOrderTime?: string
    salesOrderNote?: string
    creator?: string
    createTime?: string
    salesProducts?: string
    productDisplayList?: string[]
    productDisplayText?: string
}

const SALES_STATUS_OPTIONS = [
    { value: 0, label: '草稿', tagType: 'info' },
    { value: 1, label: '待审核', tagType: 'warning' },
    { value: 2, label: '驳回', tagType: 'danger' },
    { value: 3, label: '未入库', tagType: 'info' },
    { value: 4, label: '部分入库', tagType: 'warning' },
    { value: 5, label: '已完成', tagType: 'success' },
    { value: 6, label: '已关闭', tagType: 'danger' },
]

const loading = ref(false)
const tableData = ref<SalesOrderItem[]>([])
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<SalesOrderItem[]>([])

const advancedVisible = ref(false)

const formInline = reactive({
    salesOrderNo: '',
    salesOrderStatus: '',
    customerId: '',
    dateRange: [] as string[],
})

const advancedForm = reactive({
    salesOrderNo: '',
    salesOrderStatus: '',
    statusList: [] as number[],
    customerId: '',
    dateRange: [] as string[],
    minAmount: undefined as number | undefined,
    maxAmount: undefined as number | undefined,
    minCount: undefined as number | undefined,
    maxCount: undefined as number | undefined,
    departmentName: '',
    userName: '',
    makerName: '',
    makerTimeRange: [] as string[],
    reviewer: '',
    reviewTimeRange: [] as string[],
})

const page = reactive({
    pageindex: 1,
    pagesize: 10,
    listCount: 0,
    pageCount: 0,
})

const customerOptions = ref<any[]>([])
const customerLoading = ref(false)

const safeJsonParse = (value: any) => {
    if (value == null || value === '') return null
    if (typeof value !== 'string') return null
    const trimmed = value.trim()
    if (!(trimmed.startsWith('{') || trimmed.startsWith('['))) return null
    try {
        return JSON.parse(trimmed)
    } catch (error) {
        console.warn('解析JSON失败:', value, error)
        return null
    }
}

const toArray = (value: any): any[] => {
    if (!value && value !== 0) return []
    if (Array.isArray(value)) return value
    const parsed = safeJsonParse(value)
    if (Array.isArray(parsed)) return parsed
    if (parsed && Array.isArray(parsed.data)) return parsed.data
    if (parsed && Array.isArray(parsed.records)) return parsed.records
    if (parsed && Array.isArray(parsed.list)) return parsed.list
    if (parsed && Array.isArray(parsed.items)) return parsed.items
    return []
}

const splitNamesFromString = (value: any): string[] => {
    if (typeof value !== 'string') return []
    const sanitized = value
        .replace(/[\[\]\{\}"]/g, '')
        .replace(/productName|ProductName|goodsName|GoodsName|name|Name/gi, '')
    return sanitized
        .split(/[,，、;\n\t]+/)
        .map((item) => item.trim())
        .filter(Boolean)
}

const formatProductDisplayItem = (item: any, index?: number): string | null => {
    if (!item && item !== 0) return null

    if (typeof item === 'string') {
        const text = item.trim()
        if (!text) return null
        return text
    }

    const raw = item || {}
    const name =
        raw.productName ||
        raw.ProductName ||
        raw.goodsName ||
        raw.GoodsName ||
        raw.name ||
        raw.Name ||
        ''
    const code =
        raw.productCode ||
        raw.ProductCode ||
        raw.goodsCode ||
        raw.GoodsCode ||
        raw.code ||
        ''
    const spec =
        raw.specificationModel ||
        raw.SpecificationModel ||
        raw.productSpecification ||
        raw.productspectification ||
        raw.productUnit ||
        raw.specification ||
        ''
    const unit =
        raw.unitName ||
        raw.UnitName ||
        raw.unitDisplayName ||
        raw.unit ||
        raw.productUnitName ||
        ''
    const quantity =
        raw.quantity ??
        raw.salesQuantity ??
        raw.salesCount ??
        raw.orderQuantity ??
        raw.qty
    const price =
        raw.salePrice ??
        raw.salesPrice ??
        raw.unitPrice ??
        raw.salesUnitPrice
    const type = raw.productTypeName || raw.ProductTypeName || ''

    const detailParts = []
    if (code) detailParts.push(code)
    if (spec) detailParts.push(spec)
    if (unit) detailParts.push(unit)
    if (type) detailParts.push(type)
    if (typeof price === 'number' && !Number.isNaN(price)) detailParts.push(`¥${price}`)

    const detailText = detailParts.length ? `（${detailParts.join(' / ')}）` : ''
    const qtyText =
        typeof quantity === 'number' && Number.isFinite(quantity) && quantity > 0
            ? ` ×${quantity}`
            : ''

    const label = name || code || spec || ''
    if (!label) return null

    const prefix = typeof index === 'number' ? `${index + 1}. ` : ''
    return `${prefix}${label}${detailText}${qtyText}`
}

const extractProductNames = (row: any): string[] => {
    const result: string[] = []
    const seen = new Set<string>()
    const collect = (text?: string | null) => {
        if (!text) return
        const trimmed = text.trim()
        if (!trimmed || seen.has(trimmed)) return
        seen.add(trimmed)
        result.push(trimmed)
    }

    const addFromList = (list: any[]) => {
        list.forEach((item, index) => {
            const formatted = formatProductDisplayItem(item, index)
            if (formatted) {
                collect(formatted)
            } else if (typeof item === 'string') {
                splitNamesFromString(item).forEach(collect)
            }
        })
    }

    const candidateLists = [
        row.productDisplayList,
        row.productList,
        row.productNameList,
        row.productNames,
        row.salesProducts,
        row.salesGoods,
        row.goodsDetails,
        row.salesDetails,
        row.salesOrderDetails,
        row.detailList,
        row.details,
        row.items,
    ]

    candidateLists.forEach((candidate) => {
        if (!candidate && candidate !== 0) return
        if (Array.isArray(candidate)) {
            addFromList(candidate)
            return
        }
        if (typeof candidate === 'string') {
            const array = toArray(candidate)
            if (array.length) {
                addFromList(array)
            } else {
                splitNamesFromString(candidate).forEach(collect)
            }
            return
        }
        if (typeof candidate === 'object') {
            const nested =
                candidate?.data ||
                candidate?.list ||
                candidate?.records ||
                candidate?.items ||
                candidate?.goodsDetails ||
                candidate?.salesOrderDetails ||
                candidate?.salesDetails
            if (Array.isArray(nested)) {
                addFromList(nested)
            }
        }
    })

    if (!result.length && row.productName) {
        splitNamesFromString(String(row.productName)).forEach(collect)
    }

    return result
}

const enrichSalesOrderRows = (rows: SalesOrderItem[]): SalesOrderItem[] => {
    return rows.map((item) => {
        const productNames = extractProductNames(item)
        return {
            ...item,
            productDisplayList: productNames,
            productDisplayText: productNames.length ? productNames.join('，') : item.productName || '-',
        }
    })
}

const fetchData = () => {
    loading.value = true
    myaxios
        .get('/api/SalesOrder/GetSalesOrders', {
            params: {
                // 后端当前只必需分页参数，其余条件后续扩展时再开放
                salesOrderNo: advancedForm.salesOrderNo || formInline.salesOrderNo,
                salesOrderStatus:
                    advancedForm.statusList.length
                        ? advancedForm.statusList.join(',')
                        : (advancedForm.salesOrderStatus || formInline.salesOrderStatus),
                customerId: advancedForm.customerId || formInline.customerId,
                beginDate: advancedForm.dateRange?.[0] || formInline.dateRange?.[0] || '',
                endDate: advancedForm.dateRange?.[1] || formInline.dateRange?.[1] || '',
                pageindex: page.pageindex,
                pagesize: page.pagesize,
            },
        })
        .then((res) => {
            const result = res.data || {}
            if (result.code === 200) {
                const rows = (result.data?.data ?? []) as SalesOrderItem[]
                tableData.value = enrichSalesOrderRows(rows)
                page.listCount = result.data?.listCount ?? 0
                page.pageCount = result.data?.pageCount ?? 0
            }
        })
        .catch((err) => {
            console.error('获取销售订单列表失败:', err)
        })
        .finally(() => {
            loading.value = false
        })
}

const loadCustomers = async (keyword = '') => {
    if (customerLoading.value) return
    customerLoading.value = true
    try {
        const res = await myaxios.get('/api/Customer/GetCustomer', {
            params: {
                pageindex: 1,
                pagesize: 50,
                customerName: keyword,
            },
        })
        if (res.data.code === 200) {
            customerOptions.value = res.data.data?.data || []
        }
    } catch (error) {
        console.error('获取客户列表失败:', error)
    } finally {
        customerLoading.value = false
    }
}

const handleCustomerSearch = (keyword: string) => {
    loadCustomers(keyword)
}

const handleCustomerDropdownVisible = (visible: boolean) => {
    if (visible && !customerOptions.value.length) {
        loadCustomers()
    }
}

onMounted(() => {
    fetchData()
    loadCustomers()
})

watch(
    () => [page.pageindex, page.pagesize],
    () => {
        fetchData()
    },
)

const handleQuery = () => {
    page.pageindex = 1
    fetchData()
}

const handleAdvancedReset = () => {
    advancedForm.salesOrderNo = ''
    advancedForm.salesOrderStatus = ''
    advancedForm.statusList = []
    advancedForm.customerId = ''
    advancedForm.dateRange = []
    advancedForm.minAmount = undefined
    advancedForm.maxAmount = undefined
    advancedForm.minCount = undefined
    advancedForm.maxCount = undefined
    advancedForm.departmentName = ''
    advancedForm.userName = ''
    advancedForm.makerName = ''
    advancedForm.makerTimeRange = []
    advancedForm.reviewer = ''
    advancedForm.reviewTimeRange = []
}

const handleAdvancedSearch = () => {
    page.pageindex = 1
    advancedVisible.value = false
    fetchData()
}

const handleReset = () => {
    formInline.salesOrderNo = ''
    formInline.salesOrderStatus = ''
    formInline.customerId = ''
    formInline.dateRange = []
    page.pageindex = 1
    fetchData()
}

const handleSelectionChange = (val: SalesOrderItem[]) => {
    multipleSelection.value = val
}

const handleCreate = () => {
    router.push('/CreateSalesOrder')
}

const handleEdit = (row: SalesOrderItem) => {
    router.push({
        path: '/updateSalesOrder', 
        query: { salesOrderId: row.salesOrderId },
    })
}

const handleDelete = (row: SalesOrderItem) => {
    ElMessageBox.confirm('确认删除该销售单吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                const res = await myaxios.delete('/api/SalesOrder/DeleteSalesOrder', {
                    params: { salesOrderId: row.salesOrderId },
                })
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success(result.message || '删除成功')
                    fetchData()
                } else {
                    ElMessage.error(result.message || '删除失败')
                }
            } catch (error) {
                console.error('删除销售单失败:', error)
                ElMessage.error('删除失败，请稍后重试')
            }
        })
        .catch(() => {})
}

const handleBatchDelete = () => {
    if (!multipleSelection.value.length) {
        ElMessage.warning('请选择需要删除的销售单')
        return
    }

    ElMessageBox.confirm(
        `确认删除选中的${multipleSelection.value.length}条销售单吗？`,
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        },
    )
        .then(async () => {
            try {
                // 获取选中的ID数组
                const ids = multipleSelection.value.map((item) => item.salesOrderId)
                console.log('批量删除选中的订单ID:', ids, '数量:', ids.length)
                
                // 根据其他模块的实现（如岗位、组织、角色），使用POST请求
                // 参数名使用 ids，传递数组格式
                const res = await myaxios.post('/api/SalesOrder/DeleteSalesOrders', {
                    ids: ids,
                })
                
                const result = res.data || {}
                if (result.code === 200) {
                    ElMessage.success(result.message || '批量删除成功')
                    // 清空选中状态
                    multipleSelection.value = []
                    fetchData()
                } else {
                    ElMessage.error(result.message || '批量删除失败')
                }
            } catch (error: any) {
                console.error('批量删除销售单失败:', error)
                // 如果使用 ids 参数失败，尝试使用 salesOrderIds 参数名
                if (error.response?.status === 400 || error.response?.status === 404) {
                    try {
                        const ids = multipleSelection.value.map((item) => item.salesOrderId)
                        const res = await myaxios.post('/api/SalesOrder/DeleteSalesOrders', {
                            salesOrderIds: ids,
                        })
                        const result = res.data || {}
                        if (result.code === 200) {
                            ElMessage.success(result.message || '批量删除成功')
                            multipleSelection.value = []
                            fetchData()
                        } else {
                            ElMessage.error(result.message || '批量删除失败')
                        }
                    } catch (retryError: any) {
                        console.error('重试批量删除失败:', retryError)
                        ElMessage.error(retryError.response?.data?.message || '批量删除失败，请稍后重试')
                    }
                } else {
                    ElMessage.error(error.response?.data?.message || '批量删除失败，请稍后重试')
                }
            }
        })
        .catch(() => {})
}

const handleRefresh = () => {
    multipleTableRef.value?.clearSelection?.()
    multipleSelection.value = []
    fetchData()
    ElMessage.success('已刷新销售订单列表')
}

const handleCopy = () => {
    ElMessage.warning('复制功能暂未实现')
}

const handleAudit = () => {
    ElMessage.warning('审核功能暂未实现')
}

const handleRevoke = () => {
    ElMessage.warning('撤销功能暂未实现')
}

const handleCloseOrder = () => {
    ElMessage.warning('关闭功能暂未实现')
}

const handleOpenOrder = () => {
    ElMessage.warning('开启功能暂未实现')
}

// 处理导出成功的公共方法
const handleExportSuccess = (res: any, selectedCount: number) => {
    const disposition = res.headers?.['content-disposition'] || res.headers?.['Content-Disposition']
    let fileName = `销售订单_已选_${moment().format('YYYYMMDDHHmmss')}.xlsx`
    if (disposition) {
        const match = /filename\*=UTF-8''([^;]+)|filename="?([^";]+)"?/i.exec(disposition)
        if (match) {
            const raw = match[1] ?? match[2]
            if (typeof raw === 'string' && raw.length > 0) {
                fileName = decodeURIComponent(raw)
            }
        }
    }

    const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage.success(`已成功导出选中的${selectedCount}条销售订单`)
}

const handleExport = () => {
    // 批量导出：必须选择订单才能导出
    if (!multipleSelection.value || multipleSelection.value.length === 0) {
        ElMessage.warning('请先选择要导出的销售订单')
        return
    }

    // 导出选中的订单 - 获取选中的ID数组
    const selectedIds = multipleSelection.value.map((item) => item.salesOrderId)
    console.log('批量导出 - 选中的订单ID:', selectedIds, '数量:', selectedIds.length)
    
    // 根据批量删除接口的实现方式，使用POST请求，参数名为 ids，传递数组格式
    myaxios
        .post('/api/SalesOrder/ExportSalesOrders', {
            ids: selectedIds, // 传递ID数组，与批量删除接口保持一致
        }, {
            responseType: 'blob',
        })
        .then((res: any) => {
            console.log('导出请求成功，响应数据大小:', res.data?.size || res.data?.length, '选中的订单数量:', selectedIds.length)
            handleExportSuccess(res, selectedIds.length)
        })
        .catch(async (err: any) => {
            console.error('导出销售订单失败:', err)
            console.error('错误详情:', {
                status: err.response?.status,
                statusText: err.response?.statusText,
                data: err.response?.data,
                message: err.message,
            })
            console.error('请求参数:', { ids: selectedIds, selectedCount: selectedIds.length })
            
            // 处理blob响应中的错误信息（如果后端返回了JSON错误）
            if (err.response?.data instanceof Blob) {
                try {
                    const text = await err.response.data.text()
                    const errorData = JSON.parse(text)
                    console.error('后端返回的错误信息:', errorData)
                    ElMessage.error(errorData.message || errorData.msg || '导出失败，请稍后重试')
                    return
                } catch (parseErr) {
                    console.warn('无法解析错误响应:', parseErr)
                }
            }
            
            // 尝试多种参数格式
            const tryExport = async (params: any, method: 'post' | 'get' = 'post') => {
                try {
                    if (method === 'post') {
                        const res = await myaxios.post('/api/SalesOrder/ExportSalesOrders', params, {
                            responseType: 'blob',
                        })
                        return res
                    } else {
                        const res = await myaxios.get('/api/SalesOrder/ExportSalesOrders', {
                            params: params,
                            responseType: 'blob',
                        })
                        return res
                    }
                } catch (e: any) {
                    // 检查是否是blob响应中的错误
                    if (e.response?.data instanceof Blob) {
                        try {
                            const text = await e.response.data.text()
                            const errorData = JSON.parse(text)
                            throw { ...e, parsedError: errorData }
                        } catch {
                            throw e
                        }
                    }
                    throw e
                }
            }
            
            // 方案1: 尝试使用 salesOrderIds（数组格式）
            try {
                console.warn('尝试使用 salesOrderIds（数组）参数')
                const res = await tryExport({ salesOrderIds: selectedIds }, 'post')
                handleExportSuccess(res, selectedIds.length)
                return
            } catch (err1: any) {
                console.warn('方案1失败:', err1.response?.status, err1.parsedError || err1.message)
            }
            
            // 方案2: 尝试使用 salesOrderIds（字符串格式）
            try {
                const idsString = selectedIds.join(',')
                console.warn('尝试使用 salesOrderIds（字符串）参数')
                const res = await tryExport({ salesOrderIds: idsString }, 'post')
                handleExportSuccess(res, selectedIds.length)
                return
            } catch (err2: any) {
                console.warn('方案2失败:', err2.response?.status, err2.parsedError || err2.message)
            }
            
            // 方案3: 尝试使用 GET 请求
            try {
                const idsString = selectedIds.join(',')
                console.warn('尝试使用 GET 请求')
                const res = await tryExport({ salesOrderIds: idsString }, 'get')
                handleExportSuccess(res, selectedIds.length)
                return
            } catch (err3: any) {
                console.warn('方案3失败:', err3.response?.status, err3.parsedError || err3.message)
            }
            
            // 所有方案都失败，显示错误信息
            const errorMsg = err.response?.data?.message || 
                           err.parsedError?.message || 
                           err.parsedError?.msg ||
                           err.message || 
                           '导出失败，请稍后重试'
            ElMessage.error(errorMsg)
        })
}

const goDetail = (row: SalesOrderItem) => {
    router.push({
        path: '/DetailSalesOrder',
        query: { salesOrderId: row.salesOrderId },
    })
}

const getStatusOption = (status: number) =>
    SALES_STATUS_OPTIONS.find((item) => Number(item.value) === Number(status))

const getStatusText = (status: number) => {
    return getStatusOption(status)?.label ?? '未知'
}

const getStatusTagType = (status: number) => {
    return getStatusOption(status)?.tagType ?? 'info'
}

const formatDate = (date?: string) => {
    if (!date) return ''
    return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
    if (!date) return ''
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped>
.sales-page {
    padding: 12px;
}

.toolbar {
    margin-bottom: 16px;
}

.pagination-card {
    margin-top: 16px;
}

.pagination-bar {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    gap: 16px;
}

.pagination-info {
    font-size: 12px;
    color: #666;
}

.pagination-controls {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.pagination-jump {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: #666;
}

.pagination-btn :deep(span) {
    padding: 0 10px;
}

.pagination-btn {
    border-radius: 4px;
}

.range-input {
    display: flex;
    align-items: center;
    gap: 4px;
    width: 100%;
}

.range-input :deep(.el-input-number) {
    flex: 1;
}

.range-separator {
    font-size: 12px;
    color: #666;
}

.advanced-form {
    padding-right: 8px;
}

.advanced-form :deep(.el-form-item) {
    margin-bottom: 8px;
}

.advanced-form :deep(.el-input),
.advanced-form :deep(.el-select),
.advanced-form :deep(.el-date-editor),
.advanced-form :deep(.el-input-number) {
    width: 100%;
}

.goods-column :deep(.cell) {
    white-space: normal !important;
    word-break: break-word;
    line-height: 20px;
}

.goods-multi-text {
    white-space: normal;
    word-break: break-word;
}

.goods-name-item {
    line-height: 20px;
}

/* 表格优化样式 */
:deep(.el-table) {
    font-size: 13px;
}

:deep(.el-table th) {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
    padding: 12px 0;
}

:deep(.el-table td) {
    padding: 12px 0;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
    background-color: #fafafa;
}

:deep(.el-table .el-table__row:hover > td) {
    background-color: #f5f7fa !important;
}

/* 金额文本样式 */
.amount-text {
    font-weight: 500;
    color: #f56c6c;
    font-family: 'Courier New', monospace;
}

/* 链接样式优化 */
:deep(.el-link) {
    font-weight: 500;
}

/* 标签样式优化 */
:deep(.el-tag) {
    border-radius: 4px;
    font-weight: 500;
}

/* 表格边框优化 */
:deep(.el-table--border) {
    border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
    border-right: 1px solid #ebeef5;
}

/* 固定列阴影 */
:deep(.el-table__fixed),
:deep(.el-table__fixed-right) {
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.12);
}

/* 表格卡片样式 */
.el-card {
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 优化表格滚动条 */
:deep(.el-table__body-wrapper) {
    scrollbar-width: thin;
    scrollbar-color: #c1c1c1 #f1f1f1;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
    width: 8px;
    height: 8px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
    background: #f1f1f1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
    background: #c1c1c1;
    border-radius: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
    background: #a8a8a8;
}

/* 操作按钮样式 */
:deep(.el-table .el-button--link) {
    padding: 4px 8px;
    margin: 0 4px;
    font-weight: 500;
}

:deep(.el-table .el-button--link:hover) {
    text-decoration: underline;
}

/* 工具栏按钮样式优化 */
.toolbar :deep(.el-button) {
    border-radius: 4px;
}

/* 筛选表单样式优化 */
.filter-form {
    margin-bottom: 0;
}

.filter-form :deep(.el-form-item) {
    margin-bottom: 16px;
}
</style>


